﻿using SolutionFactory.Services;

namespace SolutionFactory.UI
{
    public class TemplateInputController
    {
        private readonly IMessageBox _messageBox;
        private readonly ITemplateInputView _view;
        private TemplateInput _model;

        public TemplateInputController(ITemplateInputView view, IMessageBox messageBox)
        {
            _view = view;
            _messageBox = messageBox;
        }

        public TemplateInput Run(string[] CommandsToRun)
        {
            SetViewDefaults();
            _view.SetCommandsToRun(CommandsToRun);
            _view.CancelClicked = Canceled;
            _view.AcceptClicked = Accepted;
            _view.ShowDialog();
            return _model;
        }

        private void SetViewDefaults()
        {
            _view.TemplateName = "Template Name";
            _view.Description = "Template Description";
            _view.OutputDirectory = @"C:\temp\";
            _view.Category = "Visual C#";
            _view.SubCategory = "Line Of Business App";
        }

        private void Accepted()
        {
            CreateModelFromView();

            if (_model.IsValid())
            {
                _view.Close();
            }
            else
            {
                _messageBox.ShowError(_model.GetErrorMessage());
            }
        }

        private void CreateModelFromView()
        {
            _model = new TemplateInput();
            _model.Name = _view.TemplateName;
            _model.Description = _view.Description;
            _model.Category = _view.Category.Replace("Visual C#", "CSharp");
            _model.SubCategory = _view.SubCategory;
            _model.OutputDirectory = _view.OutputDirectory;
            _model.RunOnCompletion = _view.RunOnCompletion;
            _model.IncludeParentDirectory = _view.IncludeParentDirectory;
        }

        private void Canceled()
        {
            _model = null;
            _view.Close();
        }
    }
}